<?php
class UsersController extends AppController {
    var $name = 'Users';
    var $components = array('Session', 'Password');
    //var $scaffold;
    
    function login()
    {
        $this->layout = 'unauth';
        
        
    

    }
    function logout(){
        $this->Session->destroy();
        
        $this->redirect($this->Auth->logout());
    }
    function nonactive()
    {
        $this->layout = 'unauth';
    }
    function profile($id = null) 
    {
        if(isset($this->data))
        {
            $this->User->id = $this->data['User']['id'];
            $this->Session->setFlash('Your details have been updated.');
            $this->User->save($this->data);
        }  
        $this->set('profile', $this->User->findByid($this->Auth->user('id'))); 
        App::import('Model', 'Available');
        $av = new Available();
        $this->set('avail', $av->find('all'));
        App::import('Model', 'Skill');
        $sk = new Skill();
        $this->set('skill', $sk->find('all'));
        $this->set('skfind', $sk->User->findByid($this->Auth->user('id')));
             
    }
    function uapplication()
    {
        $this->layout = 'application';

        App::import('Model', 'Available');
        $av = new Available();
        $this->set('avail', $av->find('all'));

        App::import('Model', 'Skill');
        $sk = new Skill();
        $this->set('skill', $sk->find('all'));
        
        App::import('Model', 'Group');
        $grp = new Group();
        $grp->recursive = -1;
        $defaultGroup = $grp->findByname('User');
        //$this->set('grp', $this->User->Group->find('list'));
        
        $newpass = $this->Password->generatePassword();
        //$this->set('skills', $sk->find('all'));
        //echo "Auto generated password is: " . $newpass;

        if (!empty($this->data))
        {
            //echo pr($this->data);
            $this->data['Group']['id'] = $defaultGroup['Group']['id'];
            $formData = $this->data;
            echo pr($formData);
            if (isset($this->data['other']))
            {
                unset($this->data['other']);
            }
            echo pr($this->data);
            $this->User->save($this->data);
            $newUserid = $this->User->id;
            //if ($this->User->save($this->data)) {
            //    $this->Session->setFlash('Your user application has been saved.');
             //   $this->redirect(array('action' => 'index'));
            //}
            $this->Session->setFlash("The application has been submitted");
            $this->_sendNewUserMail($formData, $newUserid);
            $this->redirect('/users/applicationconfirmation');
        }

        
        
        
    }
    function applicationconfirmation()
    {
        $this->layout = 'unauth';
    }
    function userlist()
    {
        $this->set('ulist', $this->User->find('all'));
        $this->set('grp', $this->User->Group->find('list', array('fields' => array('Group.name', 'Group.name'))));
    }
    function searchusers()
    {
        App::import('Model', 'Skill');
    $sk = new Skill(); 
    $this->set('skill', $sk->find('all'));   
    if(isset($this->data))
    { 
              $i = 1;
              $skcheck = '\'\'';
            if(!empty($this->data['Skill']['id']))
            {
            foreach($this->data['Skill']['id'] as $sk)
            {
                if ($i == 1)
                {
                    $skcheck = '\'' . $sk . '\'';
                }
                if ($i > 1)
                {
                    $skcheck = $skcheck . ', ' . '\'' . $sk . '\'';
                }
                $i++;
            }
            }
            
        $findings = $this->User->query('Select * from users as User where not exists (select * from skills as skill where skill.id in ('. $skcheck . ') and not exists(select * from skills_users as su where User.id = su.user_id and su.skill_id = skill.id)) ORDER BY User.active DESC;');
        
        
        $this->set('found', $findings);
    }
     
    }
    function searchavail()
    {
        App::import('Model', 'Available');
    $avail = new Available(); 
    $this->set('avail', $avail->find('all'));   
    if(isset($this->data))
    { 
              $i = 1;
              $availcheck = '\'\'';
            if(!empty($this->data['Available']['id']))
            {
            foreach($this->data['Available']['id'] as $av)
            {
                if ($i == 1)
                {
                    $availcheck = '\'' . $av . '\'';
                }
                if ($i > 1)
                {
                    $availcheck = $availcheck . ', ' . '\'' . $av . '\'';
                }
                $i++;
            }
            }
            
        $findings = $this->User->query('Select * from users as User where not exists (select * from availables as available where available.id in ('. $availcheck . ') and not exists(select * from availables_users as au where User.id = au.user_id and au.available_id = available.id)) ORDER BY User.active DESC;');
        
        
        $this->set('found', $findings);
    }
     
    }
    function _sendNewUserMail($app, $id) 
    {
         //$User = $this->User->read(null,$id);
         $this->Email->to = 'yaguilar@mtnstatesgroup.org';
         //$this->Email->bcc = array('secret@example.com');
         $this->Email->subject = 'Using CakePHP for email now';
         //$this->Email->replyTo = 'kalritch@gmail.com';
         $this->Email->from = 'yaguilar@mtnstatesgroup.org';
         $this->Email->template = 'uapplication'; // note no '.ctp'
         //Send as 'html', 'text' or 'both' (default is 'text')
         $this->Email->sendAs = 'html'; // because we like to send pretty mail
         //Set view variables as normal
         //$this->Email->delivery = 'debug';
         $this->Email->layout = 'uapp';
         $this->set('app', $app);
         $this->set('usr', $this->User->findByid($id));
         //Do not pass any args to send()
         $this->Email->send();
    }
    function sendnewpass($usr)
    {
        $newpass = $this->Password->generatePassword();
        $hashpass = $this->Auth->password($newpass);
        $this->User->id = $usr;
        
        $this->User->save(array('password' => $hashpass));
        $this->_upassemail($usr, $newpass);
        $this->Session->setFlash('User has been emailed a new password');
        $this->redirect('../users/uprofile/'.$this->User->id);
        
    }
    function _upassemail($usr, $pass)
    {
        $usr = $this->User->findByid($usr);
         $this->Email->to = $usr['User']['email_address'];
         $this->Email->subject = 'Password Reset Information';
         //$this->Email->replyTo = 'kalritch@gmail.com';
         $this->Email->from = 'yaguilar@mtnstatesgroup.org';
         $this->Email->template = 'passreset'; // note no '.ctp'
         //Send as 'html', 'text' or 'both' (default is 'text')
         $this->Email->sendAs = 'html'; // because we like to send pretty mail
         //Set view variables as normal
         //$this->Email->delivery = 'debug';
         $this->set('pass', $pass);
         $this->set('usr', $usr);
         //$this->set('checkpass', $this->Auth->password($pass));
         //Do not pass any args to send()
         $this->Email->send();
    }
 function uprofile($usr = null)
 {
    $av = new Available();
    $this->set('avail', $av->find('all'));
    App::import('Model', 'Skill');
    $sk = new Skill(); 
    if(isset($this->data))
    { //echo pr($this->data);
        $this->User->id = $usr;
        $this->User->save($this->data);
        $this->Session->setFlash('Profile Saved');
        $this->redirect('../users/uprofile/'.$this->User->id);
    }
    
    $this->set('profile', $this->User->findByid($usr));
    $this->set('grp', $this->User->Group->find('list'));
    $this->set('skill', $sk->find('all'));
    //$this->set('selected', $sk->SkillsUser->findByid($usr));
    
 }
 function sprofile($usr)
 {
    $av = new Available();
    $this->set('avail', $av->find('all'));
    App::import('Model', 'Skill');
    $sk = new Skill(); 
    
    $this->set('profile', $this->User->findByid($usr));
    $this->set('grp', $this->User->Group->find('list'));
    $this->set('skill', $sk->find('all'));
    //$this->set('selected', $sk->SkillsUser->findByid($usr));
    
 }
 function newuser()
 {
    if(isset($this->data))
    {
        $this->User->save($this->data);
        $this->redirect('../users/userlist');
    }
    $this->set('grp', $this->User->Group->find('list'));
 }
 function changepassword($id) {
    //$this->autoRender = false;
    if (!empty($this->data))
    {
        $this->User->recursive = -1;
        $user = $this->User->findById($this->Auth->User('id'));
        if($this->Auth->password($this->data['User']['old_password']) == $user['User']['password'])
        {
            if ($this->data['User']['password'] == $this->data['User']['passwordconf'])
            {
                $this->data['User']['password']= $this->Auth->password($this->data['User']['password']);
                $this->User->id = $this->Auth->user('id');
                if ($this->User->save($this->data))
                {
                    $this->Session->setFlash(__('Password has been reset', true));
                    $this->redirect(array('action'=>'profile'));
                } 
                else
                {
                    $this->Session->setFlash(__('Password not reseted', true));
                }
            
            }
            else
            {
                $this->Session->setFlash(__('Passwords do not match', true));
            }
         }      
        else
        {
        $this->Session->setFlash(__('The old password is not correct. Please try again.', true));
        }
   

                if (isset($this->data['User']['password']))
                        unset($this->data['User']['password']);
                if (isset($this->data['User']['passwordconf']))
                        unset($this->data['User']['passwordconf']);
                if (isset($this->data['User']['old_password']))
                        unset($this->data['User']['old_password']);
                        //$this->redirect('../users/profile');
    }
    }
 function uchangepass($id=null)
 {
    //$this->render('changepassword');
    //$user = $this->User->findById($id);
      $this->set('password', NeatString::randomPassword(8));   
        
            //$this->data['User']['password']= $this->Auth->password($this->data['User']['password']);
//            if ($this->User->save($this->data))
//            {
//                $this->Session->setFlash(__('Password reset', true));
//                $this->redirect($this->referer());
//            } 
//            else
//            {
//                $this->Session->setFlash(__('Password not reseted', true));
//            }
//        
//            
//            
//            
//        
//
//                if (isset($this->data['User']['password']))
//                        unset($this->data['User']['password']);
                
    }
    function udelete($usr)
    {
       $this->User->id = $usr;
       $this->User->delete();
       $this->Session->setFlash('Deleted');
       $this->redirect('../users/userlist');
        
    }
    function tcount()
    { 
        $this->User->recursive=-1;
         $options['joins'] = array(
                    array('table' => 'jobs_users',
                        'alias' => 'JobsUser',
                        'type' => 'inner',
                        'conditions' => array(
                            'User.id = JobsUser.user_id'
                                            )
                    ),
                    array('table' => 'jobs',
                        'alias' => 'Job',
                        'type' => 'inner',
                        'conditions' => array(
                            'JobsUser.job_id = Job.id'
                                            )
                        )
            );
            $options['conditions'] = array(array(
                'Job.sdate >=' => date('Y-m-d H:i'), 'User.id' => $this->Auth->user('id')
                ));
        $count = $this->User->find('count', $options); 
       
        return $count;
        
    }
    function ulist($type)
    {   
        $this->layout= false;
        $this->User->recursive=-1;
         $options['joins'] = array(
                    array('table' => 'groups_users',
                        'alias' => 'GroupsUser',
                        'type' => 'inner',
                        'conditions' => array(
                            'User.id = GroupsUser.user_id'
                                            )
                    ),
                    array('table' => 'groups',
                        'alias' => 'Group',
                        'type' => 'inner',
                        'conditions' => array(
                            'GroupsUser.group_id = Group.id'
                                            )
                        )
            );
            $options['conditions'] = array(array(
                'Group.name' => $type));
            $options['order'] = array(array('User.active DESC', 'User.lname ASC'));
        
        $this->set('ulist',$this->User->find('all', $options));
        
        switch ($type)
        {
            case "Admin":
                $tname = 'Administrator';
                break;
            case "CaseManager":
                $tname = 'ANA Staff';
                break;
            case "User":
                $tname = 'Volunteers';
                break;
        }
        
        $this->set('type', $tname);
        
        
    }
    
}
?>